# -*- coding: utf-8 -*-
from base64 import b64encode

import requests
import scrapy
from urllib import request

import time
from PIL import Image
from scrapy.http import FormRequest,Request

class GuokeLoginSpider(scrapy.Spider):
    name = 'guoke_login'
    allowed_domains = ['guokr.com']
    start_urls = ['https://account.guokr.com/sign_in/']

    def parse(self, response):
        print('=' * 30)
        username = '18106951237'
        password = '951237'
        permanent = 'y'

        formdata = {
            'username': username,
            'password': password,
            'permanent': permanent
        }
        captcha_url = response.xpath('//img[@id="captchaImage"]/@src').get()
        if captcha_url:
            # formdata['captcha_rand'] = response.xpath('//input[@id="captchaRand"]').get()
            # formdata['csrf_token'] = response.xpath('//input[@id="csrf_token"]/@valueckcg').get()
            captcha = self.recognize_captcha_auto(captcha_url)
            if not captcha:
                return scrapy.Request(url=self.start_urls[0], callback=self.parse)
            else:
                formdata['captcha'] = captcha
                print(formdata['captcha'])
        # 不能有相同的url会过滤掉
        # ?????????????????????
        # 默认会获取隐藏的对象，所以这里就不要传递隐藏对象
        # yield FormRequest.from_response(response, formid="loginForm", formdata=formdata, callback=self.parse_page)
        yield FormRequest.from_response(response, formdata=formdata, callback=self.parse_page)

    # 手动验证码识别
    def recognize_captcha_hand(self, image_url):
        request.urlretrieve(image_url, 'captcha.png')
        image = Image.open('captcha.png')
        image.show()
        text = input("请输入验证码：")
        return text

    # 平台验证码识别
    def recognize_captcha_auto(self, captcha_utl):
        # 识别长度为4任意数字英文字母的验证码
        request.urlretrieve(captcha_utl, 'captcha.png')
        host = 'https://302307.market.alicloudapi.com'
        path = '/ocr/captcha'
        recognize_url = host + path
        form_data = {'length': 4}
        with open('captcha.png', 'rb') as fp:
            data = fp.read()
            image = b64encode(data)
            form_data['image'] = image

        form_data['type'] = 1001

        appcode = '50e4ccb3521f4f8bb02b68a492ec8ec7'
        headers = {
            'Authorization': 'APPCODE ' + appcode,
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        }

        response = requests.post(recognize_url, data=form_data, headers=headers)
        result = response.json()
        return result['data']['captcha']

    def parse_page(self, response):
        time.sleep(1)
        print(response.text)
        print('=' * 30)
        print(response.url)
        if response.url == 'https://account.guokr.com/sign_in/':
            content = response.xpath('//head/meta[@http-equiv="Refresh"]/@content').get()
            # print(type(content))
            # print(content)
            url = str(content)[3:]
            print(url)
            yield Request(url, callback=self.parse_guokr_page)

        else:
            print("登录失败")

    def parse_guokr_page(self,response):
        title = response.xpath('//head/title/text()').get()
        if title == '果壳 科技有意思':
            print('登录成功')
        else:
            print("登录失败")